package com.wontube.web.verify;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

/**
 * @author tanggf(2012-5-8)
 *
 */
public class KeyCodeImage {
	private final static String formatName = "png";
	private final static Color[] fontColors = new Color[]{
		new Color(0, 205, 0), new Color(238, 44, 44), new Color(0, 139, 139), 
		new Color(121, 205, 205), new Color(50, 205, 50)
	};	
	private final static Color bgColor = new Color(232, 232, 232);		
	
	public static void outputImage(String text, OutputStream output){
		int width = 100;
		int height = 25;		
		Color fontColor = fontColors[new Random().nextInt(fontColors.length)];
		BufferedImage image = createImage(width, height, bgColor, fontColor, text);
		try {
			ImageIO.write(image, formatName, output);
		} catch (IOException e) {			
		}
	}
	
	private static BufferedImage createImage(int width, int height, Color bgColor, Color fontColor, String text){
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.createGraphics();
		g.setColor(bgColor);
		g.fillRect(0, 0, width, height);
		
		g.setColor(fontColor);
		g.setFont(new Font(Font.SERIF, Font.BOLD, 20));
		
		g.drawString(text, 15, 20);	
		g.dispose();
		return image;		
	}
}
